
/*
* 贷后管理首页 台账 js
*
* */
var layer;
var table;
var basePath;
var vm;
var templateCode;
var tableColum;
window.layinit(function (htConfig) {
    var _htConfig = htConfig;
    basePath = _htConfig.coreBasePath;
    uiBasePath = _htConfig.uiBasePath;
    vm = new Vue({
        el: '#app',
        data: {
            loading: false,
            exporting: false,//导出标志位
            searchForm: {
                tableName: ''  //表格名称

            },
         // 文件上传
            uploadSalaryModel:false,
            uploadSalarySetForm:{
            	timeYearMonth:'',
            	uploadType: '',
                templateCode:'',
                uploadSalaryFile:null,
                salaryFileType:'',
            },
            templateList:[],

            uploadSalarySetFormValidate:{
            	timeYearMonth: [
                    { required: true, message: '请选择时间'},
                ],
                templateCode: [
                    { required: true, message: '请选择模板'},
                ],
                uploadType: [
                    { required: true, message: '请选择导入方式'},
                ],
                uploadSalaryFile: [
                    { required: true, message: '请选择导入文件'},
                ]
            },
            errorDataLog:[],
            errorFlagList:[],
            fileId:'',
            templateCode:'',
            
            // 上传错误数据
            uploadErrorDataModel:false,
            uploadErrorFile:false,
        },

        methods: {
            //重载表格
            toLoading: function () {
                if (table == null) {
                    return;
                }
                var self = this;
                self.loading = true;
                table.reload('listTable', {
                    where: {

                        tableName: self.searchForm.tableName  //表格名称

                    }
                    , page: {
                        curr: 1 //重新从第 1 页开始
                    }
                });
            },
            handleReset: function (name) { // 重置表单
                vm.searchForm.trailerStartDate = '';
                vm.searchForm.trailerEndDate = '';

                vm.searchForm.status = '';
                //var a=$("#trailerStartDate");
                //console.log(a);
                //alert(JSON.stringify(a));
                var tt = this.$refs[name];
                vm.toLoading();
            },
            ////  ----   单行操作界面显示  结束 -----------------
            clickExport: function () {//导出Excel表格

            },
            init: function () {
                var self = this;

                //使用layerUI的表格组件
                layui.use(['layer', 'table', 'ht_ajax', 'ht_auth', 'ht_config'], function () {
                    layer = layui.layer;
                    table = layui.table;
                    //执行渲染
                    table.render({
                        elem: '#listTable' //指定原始表格元素选择器（推荐id选择器）
                        , id: 'listTable'

                        , cols: [[
                             {field:'fileName', title: '表格名称',align: 'center'}
                            ,{field:'time', title: '时间', sort: true,align: 'center'}
                            ,{field:'importUserName', title: '上传人',align: 'center'}
                            ,{field:'lastUpdateTime', title: '上传时间',sort: true,align: 'center'}
                            ,{fixed:'right',title: '操作', align: 'center',toolbar:'#barTools'}
                        ]], //设置表头
                        url: basePath + 'dataImport/list',

                        page: true,
                        done: function (res, curr, count) {
                            //数据渲染完的回调。你可以借此做一些其它的操作
                            //如果是异步请求数据方式，res即为你接口返回的信息。
                            //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
                            self.loading = false;
                        }
                    });
                    table.on('tool(listTable)', function (obj) {
                        var selectedRowInfo = obj.data;
                        if(obj.event === 'dataInfo'){
                            var url="/dataImport/info?templateCode="+obj.data.templateCode;
                            self.showInfo(url,"数据详情");
                        }

                        if(obj.event === 'errorInfo'){
                            var url="/dataImport/info?templateCode="+obj.data.templateCode;
                            self.showInfo(url,"数据详情");
                        }

                    });
                })
            },

            showInfo:function (url,tile) {

                var openIndex= layer.open({
                    type: 2,
                    area: ['95%', '95%'],
                    fixed: false,
                    maxmin: true,
                    title:tile,
                    content: url
                });
            },
            
            // 导入数据
            uploadInitData:function () {
                var self = this;
                self.uploadSalaryModel = true;
                
                var self = this;
                // 获取薪资模板列表
                var url = basePath + "salaryTemplate/getTemplateListByType";
                $.ajax({
                    type: "GET",
                    url: url,
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    dataType: "json",
                    success: function (result) {
                        console.log("结果：========",result);
                        if (result.returnCode == "0000") {
                            console.log('模板列表', result.data);
                            self.templateList = result.data;
                        }else{
                            self.$Modal.error({content: '调用接口失败：' + result.msg});
                        }
                        self.toLoading();
                    },
                    error:function (data) {
                        self.$Modal.error({content: '消息：' + data});
                        self.toLoading();
                    }

                });
                
                self.uploadSalaryModel = true;
                self.uploadSalarySetForm.timeYearMonth = '';
                self.uploadSalarySetForm.uploadType = '';
                self.uploadSalarySetForm.templateCode = '';
            },
            // 获取上传工资文件对象
            beforeUpLoadFile: function (file) {
                console.log("上传前的文件：" ,  file)
                this.$refs.upload.clearFiles();
                this.uploadSalarySetForm.uploadSalaryFile = file;
            },
            // 关闭工资表上传窗口
            closeUploadSalaryModal:function(){
                this.uploadSalaryModel = false
                this.$refs['uploadSalarySetForm'].resetFields();
            },
         // 提交上传工资表前验证
            beforeUpload: function(){
                var self = this;
                var validateFlag = false;
                self.$refs["uploadSalarySetForm"].validate(function (valid){
                    if (valid) {
                        validateFlag = true;
	                } 
	            });
                if(!validateFlag){
                    return false;
                }
                if(!self.uploadSalarySetForm.uploadSalaryFile){
                    this.$Message.error('请选择上传文件！');
                    return false;
                }
                
                // 校验操作
                var url = basePath + "salaryExcel/validateUpload";
                var data = {
                		uploadType:self.uploadSalarySetForm.uploadType,
                		timeYearMonth:self.uploadSalarySetForm.timeYearMonth,
                		templateCode:self.uploadSalarySetForm.templateCode,
                };
                $.ajax({
                    type: "POST",
                    url: url ,
                    data: JSON.stringify(data),
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    dataType: "json",
                    success: function (result) {
                        console.log("结果：========",result);
                        if (result.returnCode == "0000") {
                            self.submitUpload();
                        }else{
                            self.$Modal.error({content: '消息：' + result.msg});
                        }
                        self.toLoading();
                    },
                    error:function (data) {
                        self.$Modal.error({content: '消息：' + data});
                        self.toLoading();
                    }

                });
               
            },
            
            // 上传
            submitUpload:function(){
            	 var self = this;
            	 
            	 var loadingIndex = layer.load();
            	 var url = basePath + "salaryExcel/uploadSalaryFile";
                 var formData = new FormData();
                 console.log("提交：", self.uploadSalarySetForm.uploadSalaryFile);
                 formData.append('file', self.uploadSalarySetForm.uploadSalaryFile);
                 formData.append('uploadType', self.uploadSalarySetForm.uploadType);
                 formData.append('timeYearMonth', self.uploadSalarySetForm.timeYearMonth);
                 formData.append('salaryFileType', self.uploadSalarySetForm.salaryFileType);
                 formData.append('templateCode', self.uploadSalarySetForm.templateCode);
                 
                 $.ajax({
                     type: "POST",
                     url: url,
                     data: formData,
                     contentType: false,
                     processData: false,
                     success: function (data) {
                         layer.close(loadingIndex);
                         console.log("上传返回参数  ===========",data);
                         if (data.returnCode == "0000") {
                        	 self.showInitData(self.uploadSalarySetForm.templateCode, data.data);
                             self.uploadSalaryModel = false;
                             self.$Modal.success({
                                 title: '',
                                 content: '操作成功'
                             });
                         }else if(data.returnCode == "9996"){
                        	 self.showInitData(self.uploadSalarySetForm.templateCode, data.data);
                        	 self.uploadSalaryModel = false;
                             self.$Modal.error({content: '消息：' + data.codeDesc});
                         }else{
                             self.$Modal.error({content: '消息：' + data.msg});
                         }
                         self.toLoading();
                     },
                     error:function (data) {
                         layer.close(loadingIndex);
                         self.$Modal.error({content: '操作失败，消息：' + data});
                         self.toLoading();
                     }
                 });
            },
            
            getTableColum:function (templateCode) {
                var self = this;

                var url = basePath + "salarySheet/getTableColum?templateCode="+templateCode;
                $.ajax({
                    type: "GET",
                    url: url,
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    dataType: "json",
                    success: function (result) {
                        console.log("结果：========",result);
                        if (result.returnCode == "0") {
                            tableColum = result.data;
                            console.log(tableColum);
                        }
                    }

                });
            },
            showInitData:function (templateCode,fileId) {
                var self = this;
                self.getTableColum(templateCode);
                self.showErrorInfo(fileId);
                self.fileId = fileId;
                self.templateCode = templateCode;

                //使用layerUI的表格组件
                layui.use(['layer', 'table', 'ht_ajax', 'ht_auth', 'ht_config'], function () {
                    layer = layui.layer;
                    table = layui.table;
                    //执行渲染
                    table.render({
                        elem: '#initDataTable' //指定原始表格元素选择器（推荐id选择器）
                        , id: 'initDataTable'

                        , cols: [tableColum], //设置表头
                        url: basePath + 'salarySheet/getSalaryTableData',

                        page: true,
                        where:{
                            templateCode:templateCode,
                            fileId:fileId,
                            queryType:1
                        },
                        done: function (res, curr, count) {
                            //数据渲染完的回调。你可以借此做一些其它的操作
                            //如果是异步请求数据方式，res即为你接口返回的信息。
                            //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度

                            var errorData = self.errorFlagList;
                            $(".layui-table-body.layui-table-main tr td").each(function () {

                                var field = $(this)[0].dataset.field+"";
                                var jobCode = $(this).parent().first()[0].childNodes[2].innerText+"";

                                var errorStr = field.trim()+jobCode.trim();

                                for(var i=0;i<errorData.length;i++){
                                    if(errorStr === errorData[i]){
                                        $(this).css({color: 'red', 'font-weight':"bold", 'font-size': '20px'})
                                    }
                                }
                                var logData = self.errorDataLog;

                                $(this).hover(function (obj) {
                                    var fileId = obj.currentTarget.dataset.field+"";
                                    var jobCode = $(this).parent().first()[0].childNodes[2].innerText+"";
                                    for(var i=0;i<logData.length;i++){
                                        if(logData[i].dictCode == fileId.trim() && logData[i].jobCode == jobCode.trim() ){
                                            layer.tips(logData[i].content, this, {
                                                tips: [1, '#3595CC']
                                            });
                                        }
                                    }
                                });


                            });

                            self.loading = false;
                        }
                    });

                    table.on('edit(initDataTable)', function(obj){ //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
                        console.log(obj.value); //得到修改后的值
                        console.log(obj.field); //当前编辑的字段名
                        console.log(obj.data); //所在行的所有相关数据
                    });
                    table.on('tool(initDataTable)', function (obj) {
                        console.log("===========",obj);
                        var selectedRowInfo = obj.data;
                        if(obj.event === 'delete'){
                            layer.confirm('真的删除么?', function(index){
                                self.deleteForm.params.push(obj.data);
                                self.deleteSalaryData();
                                layer.close(index);
                            });
                        }

                    });
                })
            },
            //导出错误数据
            expErrorData:function () {
                var url= basePath + 'salaryExcel/exportErrorData?fileId='+ 69;
                window.open(url);
            },
            //上传更正数据页面
            uploadErrorData:function () {
            	 var self = this;
                 self.uploadErrorDataModel = true;
                 
            },
            
            // 获取上传错误文件对象
            beforeUpLoadErrorFile: function (file) {
                this.$refs.uploadError.clearFiles();
                this.uploadErrorFile = file;
            },
            // 提交错误数据
            subimtErrorData: function(){
            	var self = this ; 
            	if(!self.uploadErrorFile){
            		 self.$Message.error('请选择上传文件！');
                     return false;
                }
            
             var loadingIndex = layer.load();
           	 var url = basePath + "dataImport/uploadErrorFile";
                var formData = new FormData();
                formData.append('file', self.uploadErrorFile);
                formData.append('batchCode', self.batchCode);
                $.ajax({
                    type: "POST",
                    url: url,
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        layer.close(loadingIndex);
                        console.log("上传返回参数  ===========",data);
                        if (data.returnCode == "0000") {
                       	 self.showInitData(self.uploadSalarySetForm.templateCode, data.data);
                            self.uploadErrorDataModel = false;
                            self.$Modal.success({
                                title: '',
                                content: '操作成功'
                            });
                        }else if(data.returnCode == "9996"){
                       	 self.showInitData(self.uploadSalarySetForm.templateCode, data.data);
                       	 self.uploadErrorDataModel = false;
                            self.$Modal.error({content: '消息：' + data.codeDesc});
                        }else{
                            self.$Modal.error({content: '消息：' + data.msg});
                        }
                        self.toLoading();
                    },
                    error:function (data) {
                        layer.close(loadingIndex);
                        self.$Modal.error({content: '操作失败，消息：' + data});
                        self.toLoading();
                    }
                });
            	
            	
            },
            // 取消上传窗口
            cancelErrorData:function(){
            	var self = this ; 
            	self.$refs.uploadError.clearFiles();
            	self.uploadErrorDataModel = false;
            	self.uploadErrorFile = null ;
            },
            
            //展示错误信息列表
            showErrorInfo:function (fileId) {
                var self = this;
                //使用layerUI的表格组件
                layui.use(['layer', 'table', 'ht_ajax', 'ht_auth', 'ht_config'], function () {
                    layer = layui.layer;
                    table = layui.table;
                    //执行渲染
                    table.render({
                        elem: '#errorInfoTable' //指定原始表格元素选择器（推荐id选择器）
                        , id: 'errorInfoTable'

                        , cols: [[
                            {field: 'logId', title: '序号', width:400, fixed: 'left'}
                            ,{field: 'jobCode', title: '工号', width:400}
                            ,{field: 'msg', title: '错误类型', width:400}
                            ,{field: 'content', title: '错误详情', width:400}
                        ]], //设置表头
                        url: basePath + "dataImport/error?fileId="+fileId,

                        page: true,
                        done: function (res, curr, count) {
                            //数据渲染完的回调。你可以借此做一些其它的操作
                            //如果是异步请求数据方式，res即为你接口返回的信息。
                            //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
                            self.errorDataLog = res.data;
                            layui.each(self.errorDataLog,function (index,item) {
                                var dictCode = item.dictCode+"";
                                var jobCode = item.jobCode+"";
                                console.log("===========>>>>>>>>item",item);
                                console.log("===========>>>>>>>>dictCode",dictCode);
                                console.log("===========>>>>>>>>jobCode",jobCode);
                                console.log("===========>>>>>>>>index",index);

                                var fileAndJobCode = dictCode.trim()+jobCode.trim();
                                self.errorFlagList.push(fileAndJobCode);
                            });

                            self.loading = false;
                        }
                    });
                })
            },
            showLogs:function () {
                $("").click(function () {
                    alert(123);
                });
            },
            fresh:function () {
                var self = this;


                var url = basePath + "dataImport/newImportData";
                $.ajax({
                    type: "GET",
                    url: url,
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    dataType: "json",
                    success: function (result) {
                        console.log("结果：========",result);
                        if (result.returnCode == "0") {
                            self.fileId = result.data.fileId;
                            self.templateCode = result.data.templateCode;
                            console.log("fileId：========",result.fileId);
                            console.log("templateCode：========",result.templateCode);
                            self.showInitData(self.templateCode, self.fileId);
                        }
                    }

                });

                // self.showInitData(tem, fileId);
            }
        },

        mounted:function(){
            this.init();
            this.showLogs();
        }
    });
});
//














